package com.sunspring.jbug.service;

import com.google.common.collect.Lists;
import com.sunspring.jbug.bean.Project;
import com.sunspring.jbug.bean.UserInfo;
import com.sunspring.jbug.bo.ProjectAndUserMapping;
import com.sunspring.jbug.dto.ProjectBasicInfoDto;
import com.sunspring.jbug.mapper.ProjectMapper;
import com.sunspring.jbug.support.ContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author wulei
 * @date 2019-03-01
 **/
@Service
public class ProjectService {

    @Autowired
    private ProjectMapper projectMapper;

    /**
     * 查看我的项目
     * @return  ProjectBasicInfoDto list
     */
    public List<ProjectBasicInfoDto> getMyProjects() {
        UserInfo currentUser = ContextHolder.get();
        List<ProjectBasicInfoDto> list = projectMapper.selectByUserId(currentUser.getId());
        list.forEach(projectBasicInfoDto -> {
            projectBasicInfoDto.setCreatorName(projectMapper.selectCreateUser(projectBasicInfoDto.getId()));
        });
        return list;
    }

    /**
     * 创建项目
     * @param project project basic info
     */
    @Transactional
    public Integer createProject(Project project) {
        //新增项目信息
        projectMapper.add(project);
        UserInfo currentUser = ContextHolder.get();
        //添加本人到项目成员
        ProjectAndUserMapping mapping = ProjectAndUserMapping.builder()
                .projectId(project.getId())
                .userId(currentUser.getId())
                .roleId(currentUser.getRole())
                .build();
        List<ProjectAndUserMapping> list = Lists.newArrayListWithCapacity(1);
        list.add(mapping);
        addProjectMember(list);
        return project.getId();
    }

    /**
     * 新增项目成员
     * @param list ProjectAndUserMapping List
     */
    public void addProjectMember(List<ProjectAndUserMapping> list) {
        projectMapper.addBatchMember(list);
    }

}
